<template>
  <view class="coupon-page">
    <!-- 导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="left" @click="goBack">
          <wd-icon name="arrow-left" size="36rpx" />
        </view>
        <view class="center">选择优惠券</view>
        <view class="right"></view>
      </view>
    </view>

    <!-- 页面内容 -->
    <view class="page-content" :style="{ paddingTop: navigationBarHeight + 'px' }">
      <!-- 优惠券列表 -->
      <scroll-view scroll-y class="coupon-list" :style="{ height: scrollHeight + 'px' }">
        <!-- 可用优惠券 -->
        <block v-if="availableCoupons.length > 0">
          <view class="section-title">可用优惠券 ({{ availableCoupons.length }})</view>
          <view v-for="coupon in availableCoupons" :key="coupon.id" class="coupon-item"
            :class="{ active: selectedCouponId === coupon.id }" @click="selectCoupon(coupon)">
            <view class="left">
              <view class="amount">
                <template v-if="coupon.discountType === 1">
                  <text class="symbol">¥</text>
                  <text class="number">{{ formatPrice(coupon.discountAmount) }}</text>
                </template>
                <template v-else>
                  <text class="number">{{ formatPrice(coupon.discountAmount) }}</text>
                  <text class="symbol">折</text>
                </template>
              </view>
              <view class="condition">满{{ formatPrice(coupon.minPurchaseAmount) }}可用</view>
            </view>
            <view class="right">
              <view class="top">
                <text class="name">{{ coupon.name }}</text>
              </view>
              <view class="middle">
                <view class="coupon-info">
                  <view v-if="coupon.sameCouponCount > 1" class="count-badge">
                    <text class="count-text">共 {{ coupon.sameCouponCount }} 张</text>
                  </view>
                  <text class="expire-time">{{ formatDate(coupon.endDate) }}</text>
                </view>
                <view class="select-status">
                  <view v-if="selectedCouponId === coupon.id" class="selected">
                    <wd-icon name="check" color="#fff" size="32rpx" />
                  </view>
                  <view v-else class="unselected"></view>
                </view>
              </view>
              <view class="bottom">
                <text class="scope">{{ coupon.description }}</text>
              </view>
            </view>
          </view>
        </block>

        <!-- 不可用优惠券 -->
        <block v-if="unavailableCoupons.length > 0">
          <view class="section-title">不可用优惠券 ({{ unavailableCoupons.length }})</view>
          <view v-for="coupon in unavailableCoupons" :key="coupon.id" class="coupon-item unavailable">
            <view class="left">
              <view class="amount">
                <template v-if="coupon.discountType === 1">
                  <text class="symbol">¥</text>
                  <text class="number">{{ formatPrice(coupon.discountAmount) }}</text>
                </template>
                <template v-else>
                  <text class="number">{{ formatPrice(coupon.discountAmount) }}</text>
                  <text class="symbol">折</text>
                </template>
              </view>
              <view class="condition">满{{ formatPrice(coupon.minPurchaseAmount) }}可用</view>
            </view>
            <view class="right">
              <view class="top">
                <text class="name">{{ coupon.name }}</text>
              </view>
              <view class="middle">
                <view class="coupon-info">
                  <view v-if="coupon.sameCouponCount > 1" class="count-badge">
                    <text class="count-text">共 {{ coupon.sameCouponCount }} 张</text>
                  </view>
                  <text class="expire-time">{{ formatDate(coupon.endDate) }}</text>
                </view>
              </view>
              <view class="bottom">
                <text class="scope">{{ coupon.description }}</text>
              </view>
            </view>
            <view class="mask"></view>
            <view class="invalid-reason-bar">
              <wd-icon name="warning" size="28rpx" color="#ff6b81" />
              <text class="reason-text">不可用原因：</text>
              <text class="reason-content">{{ coupon.reason }}</text>
            </view>
          </view>
        </block>

        <!-- 空状态 -->
        <view v-if="availableCoupons.length === 0 && unavailableCoupons.length === 0" class="empty-state">
          <image src="/static/images/empty/coupon-empty.png" mode="aspectFit" />
          <text>暂无优惠券~</text>
        </view>
      </scroll-view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-bar">
      <wd-button block type="primary" @click="confirmSelection" custom-style="background: #FF2C54; border-color: #FF2C54;">
        确定
      </wd-button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getOrderCouponList } from '@/api/coupon'
import { formatPrice } from '@/utils/format'

const statusBarHeight = ref(0)
const navigationBarHeight = ref(0)
const scrollHeight = ref(0)
const selectedCouponId = ref(null)

// 移除模拟数据，改用接口数据
const coupons = ref({
  canUseCouponList: [],
  cannotUseCouponList: []
})

// 修改计算属性
const availableCoupons = computed(() => coupons.value.canUseCouponList)
const unavailableCoupons = computed(() => coupons.value.cannotUseCouponList)

// 获取优惠券列表
const fetchCoupons = async (orderAmount) => {
  try {
    const data = await getOrderCouponList(orderAmount)
    coupons.value = data
  } catch (error) {
    console.error('获取优惠券列表失败：', error)
    uni.showToast({
      title: '获取优惠券列表失败',
      icon: 'none'
    })
  }
}

// 方法
const goBack = () => {
  uni.navigateBack()
}

const selectCoupon = (coupon) => {
  if (selectedCouponId.value === coupon.id) {
    selectedCouponId.value = null
  } else {
    selectedCouponId.value = coupon.id
  }
}

const confirmSelection = () => {
  const selectedCoupon = selectedCouponId.value
    ? coupons.value.canUseCouponList.find(c => c.id === selectedCouponId.value)
    : null

  // 构建优惠券信息对象
  const couponInfo = selectedCoupon ? {
    id: selectedCoupon.id,
    name: selectedCoupon.name,
    discountType: selectedCoupon.discountType || 1, // 1:金额 2:折扣
    discountAmount: selectedCoupon.discountType === 2
      ? (selectedCoupon.discountAmount * 10).toFixed(1) // 折扣率转换为几折并保留一位小数
      : selectedCoupon.discountAmount, // 金额优惠
    minPurchaseAmount: selectedCoupon.minPurchaseAmount // 添加最低消费金额
  } : null

  uni.$emit('updateCoupon', couponInfo)
  uni.navigateBack()
}

// 修改日期格式化方法
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}.${month}.${day} ${hours}:${minutes}到期`
}

onLoad((options) => {
  // 获取订单金额和已选优惠券ID
  const { orderAmount, selectedCouponId: couponId } = options
  if (couponId) {
    selectedCouponId.value = Number(couponId)
  }

  // 获取优惠券列表
  if (orderAmount) {
    fetchCoupons(Number(orderAmount))
  }

  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight
  navigationBarHeight.value = statusBarHeight.value + 44

  const bottomBarHeight = 120
  scrollHeight.value = systemInfo.windowHeight - navigationBarHeight.value - bottomBarHeight
})
</script>

<style lang="scss">
.coupon-page {
  min-height: 100vh;
  background: #f8f8f8;

  .custom-navbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background: #fff;
    z-index: 999;

    .navbar-content {
      height: 44px;
      display: flex;
      align-items: center;
      padding: 0 30rpx;

      .left {
        width: 80rpx;
        display: flex;
        align-items: center;
      }

      .center {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: 500;
      }

      .right {
        width: 80rpx;
      }
    }
  }

  .section-title {
    padding: 20rpx 30rpx;
    font-size: 28rpx;
    color: #666;
  }

  .coupon-list {
    padding: 20rpx 0;

    .coupon-item {
      position: relative;
      margin: 0 30rpx 20rpx;
      background: #fff;
      border-radius: 12rpx;
      overflow: hidden;
      display: flex;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

      &.active {
        background: #fff0f3;

        .select-status .selected {
          background: #FF2C54;
          border-color: #FF2C54;
        }
      }

      &.unavailable {
        padding-bottom: 60rpx;

        .invalid-reason-bar {
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          height: 60rpx;
          background: #fff5f6;
          display: flex;
          align-items: center;
          padding: 0 24rpx;
          border-top: 1px solid #ffebee;

          .reason-text {
            font-size: 24rpx;
            color: #ff6b81;
            margin-left: 8rpx;
          }

          .reason-content {
            font-size: 24rpx;
            color: #666;
          }
        }
      }

      .mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.6);
        pointer-events: none;
      }

      .left {
        width: 160rpx;
        border-right: 1px dashed #eee;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 30rpx 0;

        .amount {
          display: flex;
          align-items: baseline;
          justify-content: center;

          .symbol {
            font-size: 24rpx;
            color: #FF2C54;
          }

          .number {
            font-size: 48rpx;
            font-weight: bold;
            color: #FF2C54;
            margin: 0 4rpx;
          }
        }

        .condition {
          font-size: 22rpx;
          color: #666;
          margin-top: 10rpx;
        }
      }

      .right {
        flex: 1;
        padding: 24rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .top {
          margin-bottom: 16rpx;

          .name {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
          }
        }

        .middle {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16rpx;
          position: relative;

          .coupon-info {
            display: flex;
            align-items: center;
            gap: 12rpx;
            
            .count-badge {
              background: rgba(255, 44, 84, 0.1);
              border: none;
              border-radius: 20rpx;
              padding: 4rpx 16rpx;
              height: 32rpx;
              display: flex;
              align-items: center;
              
              .count-text {
                color: #FF2C54;
                font-size: 20rpx;
                font-weight: 500;
                line-height: 1;
              }
            }

            .expire-time {
              color: #666;
              font-size: 22rpx;
              flex: 1;
            }
          }

          .select-status {
            .selected,
            .unselected {
              width: 36rpx;
              height: 36rpx;
              border-radius: 50%;
              border: 2rpx solid #ddd;
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }
        }

        .bottom {
          .scope {
            color: #999;
            font-size: 24rpx;
          }
        }
      }
    }
  }

  .empty-state {
    padding: 120rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;

    image {
      width: 240rpx;
      height: 240rpx;
      margin-bottom: 20rpx;
    }

    text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    padding: 20rpx 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
}
</style>